package ieco.daoimpl;

import ieco.dao.Dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

@SuppressWarnings("serial")
public abstract class DaoImpl<K, E> implements Dao<K, E> {

	private Class<E> entityClass;

	@PersistenceContext(unitName = "options")
	private EntityManager entityManager;

	public DaoImpl(Class<E> entityClass) {
		this.entityClass = entityClass;
	}

	@Override
	public E enregistrer(E entity) {
		entityManager.persist(entity);
		return entity;
	}

	@Override
	public E mettreAJour(E entity) {
		entityManager.merge(entity);
		return entity;
	}
	
	protected E find(String query, Object... params) {
		try {
			TypedQuery<E> queryAExec = entityManager.createQuery(query,
					entityClass);
			for (int i = 0; i < params.length; i++) {
				queryAExec.setParameter(i + 1, params[i]);
			}
			return (E) queryAExec.getSingleResult();
		} catch (NoResultException e) {
			return null;
		} catch (NonUniqueResultException e) {
			return null;
		}
	}

	protected List<E> findAll(String query, Object... params) {
		TypedQuery<E> queryAExec = entityManager
				.createQuery(query, entityClass);
		for (int i = 0; i < params.length; i++) {
			queryAExec.setParameter(i + 1, params[i]);
		}
		return queryAExec.getResultList();
	}

}
